package net.koodar.forge.business.category.manager;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.koodar.forge.business.category.dao.CategoryMapper;
import net.koodar.forge.business.category.model.entity.Category;
import org.springframework.stereotype.Service;
import org.webjars.NotFoundException;

import java.util.List;

/**
 * @author liyc
 */
@Service
public class CategoryManager extends ServiceImpl<CategoryMapper, Category> {

    public Category findByParentIdAndCode(Long parentId, String code) {
        List<Category> categories = baseMapper.selectList(Wrappers.<Category>lambdaQuery().eq(Category::getParentId, parentId).eq(Category::getCode, code));
        return categories.isEmpty() ? null : categories.get(0);
    }

    public Category findById(Long id) {
        Category category = baseMapper.selectById(id);
        if (category == null) {
            throw new NotFoundException("分类不存在");
        }
        return category;
    }

    public List<Category> findByParentId(Long id) {
        return baseMapper.selectList(Wrappers.<Category>lambdaQuery().eq(Category::getParentId, id));
    }

    public Long countByParentId(Long parentId) {
        return baseMapper.selectCount(Wrappers.<Category>lambdaQuery().eq(Category::getParentId, parentId));
    }
}
